package com.example.morealipy.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.morealipy.R;
import com.example.morealipy.adapter.AdapterColSpanLookup;
import com.example.morealipy.adapter.ApplyAdapter;
import com.example.morealipy.adapter.ApplyAllAdapter;
import com.example.morealipy.animation.MydefaultAnimator;
import com.example.morealipy.app.App;
import com.example.morealipy.callback.ItemDragHelperCallback;
import com.example.morealipy.constant.Constant;
import com.example.morealipy.interfaces.ApplyView;
import com.example.morealipy.interfaces.LoadApplyInterface;
import com.example.morealipy.model.ApplySaveType;
import com.example.morealipy.model.ApplyTable;
import com.example.morealipy.util.ACache;
import com.example.morealipy.util.LoadApplyImpl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class MoreActivity extends Activity implements ApplyView {
    private RecyclerView mRv_head;
    //    private LinearLayout mlinead_dynamic;
    private TextView mTv_edit;
    private Context context;
    //头部适配器
//    private ApplyHeadAdapter headAdapter;
    //全部适配器

    private ApplyAllAdapter mApplyAllAdapter;
    private LoadApplyInterface mPresenter;
    //
    private List<ApplyTable> allTablesApply;
    //存贮修改过程中
    private List<ApplyTable> headTables;
    private List<ApplyTable> mlistApplySave;
    ApplyAdapter allAdapter = null;
    //存贮adapterlist
    private List<ApplyAdapter> madapterList;
    private List<TextView> mListTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more);
        findView();
        initData();
    }

    private void initData() {
        madapterList = new ArrayList<>();
        mListTextView = new ArrayList<>();
        //存贮到内存的集合对象
        mlistApplySave = new ArrayList<>();
        allTablesApply = new ArrayList<>();
        mPresenter = new LoadApplyImpl(this);
        mPresenter.lodeApplyRequest();
    }

    private void findView() {
        mRv_head = findViewById(R.id.mRv_head);
        mTv_edit = findViewById(R.id.mTv_edit);
        mTv_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTv_edit.setText("编辑".equals(mTv_edit.getText())?"完成":"编辑");
                allAdapter.setEdit(!allAdapter.getEdit());
            }
        });
    }

    /**
     * 头部
     *
     * @param _headTables
     */
    @Override
    public void returnMineApply(List<ApplyTable> _headTables) {
    }

    /**
     * 全部
     *
     * @param _allTables
     */
    @Override
    public void returnMoreNewsApply(List<ApplyTable> _allTables, List<ApplyTable> _allUseTables, ArrayList<ApplySaveType> appayTableUserSave) {
        CreateRecycleView(_allTables, _allUseTables, appayTableUserSave);
    }

    //动态生成底部添加视图
    private void CreateRecycleView(List<ApplyTable> _allTables, final List<ApplyTable> _allUseTables, final ArrayList<ApplySaveType> appayTableUserSave) {
        if (_allTables == null || _allTables.size() == 0) {
            return;
        }
        //全局赋值
        this.allTablesApply = _allTables;
        if (null == allAdapter) {
            /**设置全部数据适配器*/
            allAdapter = new ApplyAdapter(this, allTablesApply);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false);
            mRv_head.setLayoutManager(gridLayoutManager);
            mRv_head.setItemAnimator(new MydefaultAnimator());
            AdapterColSpanLookup mAdapterColSpanLookup = new AdapterColSpanLookup(allAdapter);
            gridLayoutManager.setSpanSizeLookup(mAdapterColSpanLookup);
            mRv_head.setAdapter(allAdapter);
            ItemDragHelperCallback callback = new ItemDragHelperCallback(allAdapter);
//            //是一个工具类，可实现侧滑删除和拖拽移动,完成后数据的刷新（UI更新）由重写的ItemDragHelperCallback完成
            ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
//            //调用ItemTouchHelper的attachToRecyclerView方法建立联系
            touchHelper.attachToRecyclerView(mRv_head);
            allAdapter.setItemDragHelperCallback(callback);
        }
        allAdapter.notifyDataSetChanged();
        //获取全部列表(除去上面的已选择)
        final ArrayList<ApplySaveType> appayTableUnUser = (ArrayList<ApplySaveType>) ACache.get(App.getAppContext()).getAsObject(Constant.APPLY_ALL);
        //
        final ArrayList<ApplyTable> applyTemp = new ArrayList<>();
        allAdapter.setOnItemClickListenerEdit(new ApplyAdapter.OnItemClickListenerEdit() {

            private ArrayList<ApplyTable> appayTableUser;

            @Override
            public void onItemClick(View view, int position) {
                ApplyTable at = allTablesApply.get(position);
                int itemType = at.getItemType();
                if (_allUseTables.size() >= 11 && 2 == itemType) {
                    Toast.makeText(MoreActivity.this, "最多只能添加11个", Toast.LENGTH_LONG).show();
                } else {
                    if (1 == itemType) {
                        //往下移动
                        at.setItemType(2);
                        int indexType = at.getIndexType();
                        appayTableUser = (ArrayList<ApplyTable>) _allUseTables;//我的应用
                        for (int i = 0; i < appayTableUser.size(); i++) {
                            if (at.getId().equals(appayTableUser.get(i).getId())) {
                                //从我的应用列表里边移除点击后的视图
                                appayTableUser.remove(appayTableUser.get(i));
                            }
                        }

                        //点击后的视图添加到下面列表中
                        for(int i = 0;i<appayTableUnUser.size();i++){
                            if(indexType == appayTableUnUser.get(i).getIndex()) {
                                appayTableUnUser.get(i).getmList().add(at);
                                ApplyTable tempTitle = appayTableUnUser.get(i).getmList().get(0);
                                appayTableUnUser.get(i).getmList().remove(0);
                                Collections.sort(appayTableUnUser.get(i).getmList());
                                appayTableUnUser.get(i).getmList().add(0, tempTitle);
                                break;
                            }
                        }
                        allTablesApply.clear();
                        allTablesApply.addAll(appayTableUser);
                        for (int i = 0; i < appayTableUnUser.size(); i++) {
                            if(appayTableUnUser.get(i).getmList().size() == 2){
                                appayTableUnUser.get(i).getmList().get(0).setIshidden(false);
                            }
                            allTablesApply.addAll(appayTableUnUser.get(i).getmList());
                        }
                        //移动结束的位置
                        int moveEnd = 0;
                        moveEnd = allTablesApply.indexOf(at);

                        allAdapter.notifyItemMoved(position, moveEnd);
                        allAdapter.notifyItemRangeChanged(moveEnd-1,allTablesApply.size());
                    } else if (2 == itemType) {
                        //往上移动设置为1
                        at.setItemType(1);
                        appayTableUser = (ArrayList<ApplyTable>) _allUseTables;
                        if (appayTableUser == null) {
                            appayTableUser = new ArrayList<>();
                        }
                        appayTableUser.add(at);
                        int indexType = at.getIndexType();
                        for(int i = 0;i < appayTableUnUser.get(indexType).getmList().size();i++){
                            if (at.getId().equals(appayTableUnUser.get(indexType).getmList().get(i).getId())) {
                                appayTableUnUser.get(indexType).getmList().remove(i);
                                break;
                            }
                        }
                        allTablesApply.clear();
                        allTablesApply.addAll(appayTableUser);
                        for (int i = 0; i < appayTableUnUser.size(); i++) {
                            if(appayTableUnUser.get(i).getmList().size()==1) {
                                //隐藏title
                                appayTableUnUser.get(i).getmList().get(0).setIshidden(true);
                            }
                            allTablesApply.addAll(appayTableUnUser.get(i).getmList());
                        }
                        allAdapter.notifyItemMoved(position, appayTableUser.size() - 1);
                        allAdapter.notifyItemRangeChanged(0,position+1);

                    }

                    //进行添加或删除操作后，要更新的列表 进行存储
                    mPresenter.onItemAddOrRemove((ArrayList<ApplyTable>) allTablesApply, appayTableUser, appayTableUnUser);
                }
            }
        });
        allAdapter.setOnItemClickListener(new ApplyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, String name) {
                Toast.makeText(MoreActivity.this, name, Toast.LENGTH_LONG).show();
            }
        });
    }
}
